package com.nbst.comnutil;

import java.util.*;

public class WeekUtil {

    // 计算该周是第几周 某月的第一周以该月内的第一个周一开始
    public static int weekNoCount(Calendar cal) {
        int ans = 1;
        cal = getFirstDay(cal);
        int omonth = cal.get(Calendar.MONTH);
        while (true) {
            cal.add(Calendar.DATE, -7);
            if (cal.get(Calendar.MONTH) == omonth) {
                ans++;
            } else break;
        }
        return ans;
    }

    //
    public static int yearNoCount(Calendar cal){
        cal = getFirstDay(cal);
        return cal.get(Calendar.YEAR);
    }

    public static int monthNoCount(Calendar cal) {
        cal = getFirstDay(cal);
        return cal.get(Calendar.MONTH) + 1;
    }

    // 得到某天所属周的第一天 从周一开始。
    public static Calendar getFirstDay(Calendar cal) {
        int step;
        if (cal.get(Calendar.DAY_OF_WEEK) == 1) step = -6;
        else step = 2 - cal.get(Calendar.DAY_OF_WEEK);
        cal.add(Calendar.DATE, step);
        return cal;
    }

    public static List<String> returnAllDays(String date){
        String[] split = date.split("-");
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(split[0]), Integer.parseInt(split[1]) - 1, Integer.parseInt(split[2]));
        cal = WeekUtil.getFirstDay((Calendar) cal.clone());
        List<String> allDays=new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            StringBuilder sb = new StringBuilder();
            sb.append(cal.get(Calendar.YEAR));
            sb.append('-');
            int month = cal.get(Calendar.MONTH) + 1;
            sb.append(month / 10 == 0 ? "0" + month : month);
            sb.append('-');
            int d = cal.get(Calendar.DATE);
            sb.append(d / 10 == 0 ? "0" + d : d);
            allDays.add(sb.toString());
            cal.add(Calendar.DATE, 1);
        }
        return allDays;
    }

}
